package com.itheima.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.SetmealMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetmealMapper setmealMapper;
    @Override
    public void add(Setmeal setmeal) {
//        ​	1、插入套餐基本信息并返回主键
        setmealMapper.add(setmeal);
//​		2、根据用户勾选的检查组id集合和套餐id循环建立关系（可以使用批量建立关系）
        if (CollUtil.isNotEmpty(setmeal.getCheckgroupIds())) {
            setmealMapper.setSetmealAndCheckGroupBatch( setmeal.getId(),setmeal.getCheckgroupIds());
        }
    }

    @Override
    public List<Setmeal> getSetmeal() {
        return setmealMapper.getSetmeal();
    }

    @Override
    public Setmeal findById(Integer id) {
//        # 1、根据套餐id查询套餐详情
        Setmeal setmeal = setmealMapper.findById(id);
        if(setmeal != null){
//        # 2、我还需要根据套餐id查询套餐关联的检查组
            List<CheckGroup> checkGroups = setmealMapper.findCheckGroupBySetmealId(id);
            setmeal.setCheckGroups(checkGroups);

            if(CollectionUtil.isNotEmpty(checkGroups)){
                //        # 3、我还需要根据检查组id查询检查组关联的检查项
                for (CheckGroup checkGroup : checkGroups) {
                    List<CheckItem> checkItems = setmealMapper.findCheckItemByCheckGroupId(checkGroup.getId());
                    checkGroup.setCheckItems(checkItems);
                }
            }


        }
        return setmeal;
    }
}
